package com.fanshe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo5 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        // 获取class字节码对象
        Class<?> c = Class.forName("com.fanshe.Student");
        // 获取构造方法
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        // 获取成员变量name
        Field name = c.getDeclaredField("name");
        name.setAccessible(true);
        // 给成员变量name赋值
        name.set(obj, "zhou");

        // 获取成员变量age
        Field age = c.getDeclaredField("age");
        age.setAccessible(true);
        // 给成员变量age赋值
        age.set(obj, 30);

        // 获取成员变量address
        Field address = c.getDeclaredField("address");
        address.setAccessible(true);
        // 给成员变量address赋值
        address.set(obj, "西安");
        System.out.println(obj);
    }
}
